package djboom.materials.display.page.work1 {
	import djboom.materials.Work;
	import djboom.materials.core.BitmapDataCore;
	import djboom.materials.core.DataCore;
	import djboom.materials.display.elements.Arrow;
	import djboom.materials.display.elements.Instruction;
	import djboom.materials.display.elements.RoundedButton;
	import djboom.materials.display.elements.SampleDragged;
	import djboom.materials.display.elements.SamplePlace;
	import djboom.materials.display.elements.Window;
	import djboom.materials.display.page.Navigation;
	import djboom.materials.display.page.Page;
	import djboom.materials.events.PageEvent;
	import djboom.materials.events.WindowEvent;

	import com.greensock.TweenLite;
	import com.greensock.easing.Cubic;

	import org.casalib.display.CasaBitmap;
	import org.casalib.display.CasaSprite;
	import org.casalib.util.ArrayUtil;
	import org.casalib.util.StageReference;

	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;

	/**
	 * .
	 * <br>
	 * 
	 * @author DJ BooM 
	 * @since 28.04.2010
	 * 
	 */

	public class Page4 extends Page {

		// ----------------------------------------------------------------------------
		// Константы класса.
		// ----------------------------------------------------------------------------

		private static const INSTRUCTION_XML:XML = <instructions>
            <instruction>
                <text><![CDATA[Расположите материалы в ряд по убыванию средней плотности]]></text>       
            </instruction>            
        </instructions>;

		// ----------------------------------------------------------------------------
		// Свойства класса.
		// ----------------------------------------------------------------------------

		private var _instruction:Instruction;

		private var _arrowLeft:Arrow;
		private var _arrowRight:Arrow;

		private var _samplesDragged:CasaSprite;

		private var _draggedSample:SampleDragged;
		private var _samplePlaces:CasaSprite;
		private var _samplePlacesArray:Array = [];
		private var _samplesBitmap:CasaBitmap;

		private var _simpleButton:RoundedButton;

		private var _hardnessArray:Array = [];
		private var _sortHardness:Array = [];
		
		private var _window:Window;

		// ----------------------------------------------------------------------------
		// Конструктор.
		// ----------------------------------------------------------------------------

		public function Page4() {
			super();
		}	 

		// ----------------------------------------------------------------------------
		// Методы класса.
		// ----------------------------------------------------------------------------

		/**
		 * Реализация функции ReleaseOutside.
		 * 
		 */

		private function captureMouseUp(event:MouseEvent):void {
			if (event.target == _draggedSample || _draggedSample.contains(DisplayObject(event.target))) {
			} else {
				stopDragSample();
			}
		}

		private function setupDragSample(event:MouseEvent):void {
			_draggedSample = event.currentTarget as SampleDragged;
			
			// Поднимаем на верх.
			_samplesDragged.addChild(_draggedSample);
			
			_draggedSample.startDrag(false, new Rectangle(-197, -55, Work.WIDTH - _draggedSample.width + 75, Work.HEIGHT - 82 - _instruction.height - 52 - _draggedSample.height));
            
			StageReference.getStage().addEventListener(MouseEvent.MOUSE_UP, captureMouseUp);
		}

		private function stopDragSample(event:MouseEvent = null):void {
			_draggedSample.stopDrag();
			
			checkHitTest();
            
			StageReference.getStage().removeEventListener(MouseEvent.MOUSE_UP, captureMouseUp);
		}

		private function checkHitTest():void {
			for each (var samplePlace:SamplePlace in _samplePlacesArray) {
				if (samplePlace.free) {
					if (_draggedSample.hitTestObject(samplePlace)) {
						samplePlace.free = false;
						
						samplePlace.draggedSample = _draggedSample;
						
						_sortHardness.push(int(_draggedSample.hardness));
                    
						TweenLite.to(_draggedSample, 0.4, {x: samplePlace.x + 6, y: 245, ease: Cubic.easeInOut});
                    
						_draggedSample.removeEventListeners();
						_draggedSample.useHandCursor = false;
						_draggedSample.buttonMode = true;
						break;
					} else {
						sampleComeBack();
					}
				} else {
					sampleComeBack();
				}
			}
			
			var countFreePlace:int = 0;
			
			for each (var samplePlaceRepeat:SamplePlace in _samplePlacesArray) {
				if (samplePlaceRepeat.free) {
					countFreePlace++;
				}
			}
			
			if (countFreePlace == 0) {
				_simpleButton = new RoundedButton("Продолжить");
				_simpleButton.x = Work.WIDTH * 0.5 - _simpleButton.width * 0.5;
				_simpleButton.y = Work.HEIGHT - 118;
				_simpleButton.addEventListener(MouseEvent.CLICK, checkHardness);
				addChild(_simpleButton);
			}
		}

		private function sampleComeBack():void {
			TweenLite.to(_draggedSample, 0.3, {x: _draggedSample.initX, y: 0, motionBlur: true, ease: Cubic.easeInOut});
		}

		private function checkHardness(event:MouseEvent):void {
			_sortHardness.sort(Array.NUMERIC | Array.DESCENDING);
			
			for each (var samplePlace:SamplePlace in _samplePlacesArray) {
				_hardnessArray.push(int(samplePlace.draggedSample.hardness));
			}
			
			lockPage();
            
			_window = new Window();
            
			if (ArrayUtil.equals(_sortHardness, _hardnessArray)) {
				Navigation.toggleEnabled(Page.WORK_1_PAGE_1, false);
				
				var enableWork2:String = XML(XMLList(Navigation.NAVIGATION_XML.child("item").(@page == Page.WORK_2_PAGE_1))[0]).attribute("enable").toString();			
				if (enableWork2 == "false") {
					Navigation.toggleEnabled(Page.WORK_3_PAGE_1, true);
				}
			
				_window.addEventListener(WindowEvent.CLOSE, navigationPage);
				_window.init("Поздравляем!", "Вы успешно справились с работой №1, можете приступить к следующей.");
			} else {
				_window.addEventListener(WindowEvent.CLOSE, refreshPage);
				_window.init("Внимание!", "Расположение не верно");
			}
			
			addChild(_window);
		}

		private function refreshPage(event:WindowEvent):void {
			var pageEvent:PageEvent = new PageEvent(PageEvent.CHANGE);
			pageEvent.pageName = Page.WORK_1_PAGE_4;            
			dispatchEvent(pageEvent);
		}

		private function navigationPage(event:WindowEvent):void {
			var pageEvent:PageEvent = new PageEvent(PageEvent.CHANGE);
			pageEvent.pageName = Page.NAVIGATION;            
			dispatchEvent(pageEvent);
		}

		// ----------------------------------------------------------------------------
		// Публичные методы.
		// ----------------------------------------------------------------------------

		override public function init():void {
			// Создаем заголовок страницы.
			createTitleWork("Определение средней плотности на образцах правильной геометрической формы", 1);
			
			_instruction = new Instruction(INSTRUCTION_XML.child("instruction"));
			addChild(_instruction);
			
			_arrowLeft = new Arrow();
			_arrowLeft.x = 370;			_arrowLeft.y = 460;
			addChild(_arrowLeft);
			
			_arrowRight = new Arrow();
			_arrowRight.x = 608;
			_arrowRight.y = 460;
			addChild(_arrowRight);
			
			_samplePlaces = new CasaSprite();
			_samplePlaces.x = 200;			_samplePlaces.y = 420;
			addChild(_samplePlaces);
			
			for (var i:int = 0;i < 3;i++) {
				var samplePlace:SamplePlace = new SamplePlace();
				samplePlace.x = 240 * i;
				_samplePlaces.addChild(samplePlace);	
				
				_samplePlacesArray.push(samplePlace);
			}
            
			var materialsList:XMLList = DataCore._materialsWork1XML.child("material").(@select == "true");
            
			_samplesDragged = new CasaSprite();
			_samplesDragged.x = 160;			_samplesDragged.y = 180;
			addChild(_samplesDragged);
            
			for each (var sampleXML:XML in materialsList) {
				var name:String = sampleXML.attribute("name").toString();
				var bitmapdata:String = sampleXML.attribute("bitmapdata").toString();
				var averageHardness_KG:String = sampleXML.attribute("averageHardness_KG").toString();
                
				var sampleDragged:SampleDragged = new SampleDragged(name, BitmapDataCore.getBitmapData(bitmapdata), averageHardness_KG);
				sampleDragged.addEventListener(MouseEvent.MOUSE_DOWN, setupDragSample);
				sampleDragged.addEventListener(MouseEvent.MOUSE_UP, stopDragSample);
                
				try {
					var lastSample:SampleDragged = _samplesDragged.getChildAt(_samplesDragged.numChildren - 1) as SampleDragged;
					sampleDragged.x = lastSample.x + 240;
				} catch(error:Error) {
				}
				
				sampleDragged.initX = sampleDragged.x;
				
				_samplesDragged.addChild(sampleDragged);
			}
			
			var samplesBitmapData:BitmapData = new BitmapData(_samplesDragged.width, _samplesDragged.height, true, 0);
			samplesBitmapData.draw(_samplesDragged);
			
			_samplesBitmap = new CasaBitmap(samplesBitmapData);
			_samplesBitmap.x = 160;
			_samplesBitmap.y = 180;
			_samplesBitmap.alpha = 0.4;
			addChild(_samplesBitmap);
			
			addChild(_samplesDragged);
		}

		override protected function clearPage(event:Event):void {
			super.clearPage(event);
            
			_instruction.destroy();
			_instruction = null;
			
			_arrowLeft.destroy();
			_arrowLeft = null;
			
			_arrowRight.destroy();
			_arrowRight = null;
			
			if (_samplesDragged != null) {
				while (_samplesDragged.numChildren) {
					var sampleDragged:SampleDragged = _samplesDragged.getChildAt(0) as SampleDragged;
                
					sampleDragged.destroy();
					sampleDragged = null;
				}
            
				_samplesDragged.destroy();
				_samplesDragged = null;
			}
			
			if (_samplePlaces != null) {
				while (_samplePlaces.numChildren) {
					var samplePlace:SamplePlace = _samplePlaces.getChildAt(0) as SamplePlace;
                
					samplePlace.destroy();
					samplePlace = null;
				}
            
				_samplePlaces.destroy();
				_samplePlaces = null;
			}
			
			_samplesBitmap.destroy();
			_samplesBitmap = null;
			
			_simpleButton.destroy();
			_simpleButton = null;
		}
        
		// ----------------------------------------------------------------------------
        // Публичные свойства.
        // ----------------------------------------------------------------------------
	}
}
